package cloud.seri.auth.service

import cloud.seri.auth.domain.Menu
import cloud.seri.auth.repository.MenuRepository
import cloud.seri.auth.service.dto.MenuDTO
import cloud.seri.auth.service.mapper.MenuMapper
import org.slf4j.LoggerFactory

import org.springframework.stereotype.Service

import java.util.Optional

/**
 * Service Implementation for managing [Menu].
 */
@Service
class MenuService(
    val menuRepository: MenuRepository,
    val menuMapper: MenuMapper
) {

    private val log = LoggerFactory.getLogger(MenuService::class.java)

    /**
     * Save a menu.
     *
     * @param menuDTO the entity to save.
     * @return the persisted entity.
     */
    fun save(menuDTO: MenuDTO): MenuDTO {
        log.debug("Request to save Menu : {}", menuDTO)

        var menu = menuMapper.toEntity(menuDTO)
        menu = menuRepository.save(menu)
        return menuMapper.toDto(menu)
    }

    /**
     * Get all the menus.
     *
     * @return the list of entities.
     */
    fun findAll(): MutableList<MenuDTO> {
        log.debug("Request to get all Menus")
        return menuRepository.findAll()
            .mapTo(mutableListOf(), menuMapper::toDto)
    }


    /**
     *  Get all the menus where Parent is `null`.
     *  @return the list of entities.
     */
    fun findAllWhereParentIsNull(): MutableList<MenuDTO>  {
        log.debug("Request to get all menus where Parent is null")
        return menuRepository.findAll()
            .asSequence()
            .filter { it.parent == null }
            .mapTo(mutableListOf()) { menuMapper.toDto(it) }
    }

    /**
     * Get one menu by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
    fun findOne(id: String): Optional<MenuDTO> {
        log.debug("Request to get Menu : {}", id)
        return menuRepository.findById(id)
            .map(menuMapper::toDto)
    }

    /**
     * Delete the menu by id.
     *
     * @param id the id of the entity.
     */
    fun delete(id: String) {
        log.debug("Request to delete Menu : {}", id)

        menuRepository.deleteById(id)
    }
}
